package com.example.admin.filter;

import cn.hutool.jwt.JWT;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.Locale;


@WebFilter("/*")
@Slf4j
//通知SpringBoot 这是又一个须要管理起来的类
@Component
public class AuthFilter implements Filter {
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        log.info("AuthFilter拦截了");
        //Filter的业务
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        //查看是否带有放行信号
        Boolean flag = (Boolean) request.getAttribute("flag");

        if (flag) {
            log.info("找到信号量，并且信号量的值是一个true");
            //放行
            filterChain.doFilter(servletRequest, servletResponse);
        }

        String requestURI = request.getRequestURI();
        log.info(requestURI);
        if ("/admin/login".equals(requestURI)) {
            //放行
            filterChain.doFilter(servletRequest, servletResponse);
        }

//        if ("get".equals(request.getMethod().toLowerCase(Locale.ROOT))) {
//            filterChain.doFilter(servletRequest, servletResponse);
//        }
        //todo 获取post请求过来的数据
        //从前端获取输入字节流
        ServletInputStream requestInputStream = request.getInputStream();
//将字节流转换为字符流,并设置字符编码为utf-8
        InputStreamReader ir = new InputStreamReader(requestInputStream, "utf-8");
//使用字符缓冲流进行读取
        BufferedReader br = new BufferedReader(ir);
//开始拼装json字符串
        String line = null;
        StringBuilder sb = new StringBuilder();
        while ((line = br.readLine()) != null) {
            sb.append(line);
        }
        //3.String(json字符串）->json对象
        HashMap<String, String> map = (HashMap) JSONObject.parse(sb.toString());
        if (map!=null){   log.info("{}", map.get("token"));
            //拿到token
            String token = map.get("token").toString();

            //开始验证token
            // 密钥
            byte[] key = "你的key".getBytes();
            // 默认验证HS265的算法
            boolean verify = JWT.of(token).setKey(key).verify();
            if(verify){
                filterChain.doFilter(servletRequest,servletResponse);
            }
            log.info("{}",verify);}


        log.info("又回到了AuthFilter");
    }
}
